import 'package:flutter/material.dart';
import 'package:sample2/components/notification/theme.dart';
import 'package:sample2/model/user_info.dart';
import 'package:sample2/utils/local_storage.dart';

class AppHelper {
  
  static const lastLoginNameKey = "lastLoginName";
  UserInfo? userInfo;
  static final AppHelper shared = AppHelper._internal();
  factory AppHelper() {
    return shared;
  }
  AppHelper._internal();

  Locale? _currentLocale;

  bool isReleaseMode(){
    return const bool.fromEnvironment("isRelease");
  }

  String getBkDomainName(){
    if(isReleaseMode()){
        return "https://findresult.asia";
    }else{
       return "http://localhost:9999";
    }
  }

  String getSocketIoAddress(){
      if(isReleaseMode()){
          return "https://findresult.asia";
      }else{
          return "http://localhost:9999";
      }
  }

  String getChatPath(){
    return "/apichat";
  }

  bool userHasLogin() {
    return userInfo != null && userInfo!.hasLogin();
  }

  Future<UserInfo?> getUserInfo() async {
    userInfo = userInfo ?? await UserInfo.fromCache();
    return userInfo;
  }

  void updateUserInfo(UserInfo ui) {
    userInfo = ui;
    ui.saveToCache();
  }

  void logout(VoidCallback onComplete) {
    LocalStorage.getShared().then((shared) {
      if (userInfo != null &&
          userInfo!.username != null &&
          userInfo!.username!.isNotEmpty) {
        userInfo!.removeFromCache();
        shared.getPrefs().setString(lastLoginNameKey, userInfo!.username!);
      } else {
        shared.getPrefs().remove(lastLoginNameKey);
      }
      userInfo = null;
    });
    onComplete.call();
  }

  Future<String?> getLastLoginName() async {
    String? username =
        (await LocalStorage.getShared()).getPrefs().getString(lastLoginNameKey);
    debugPrint("got last login name: $username");
    return username;
  }

  Locale? getCurrentLocale() {
    return _currentLocale;
  }

  String getCorrespondingFontFamilyName(String languageCode) {
    String fontFamilyName = "Roboto";
    String langCode = languageCode;
    if (langCode == "zh") {
      fontFamilyName = "NotoSansTC";
    }
    return fontFamilyName;
  }

  void updateCurrentLocale(BuildContext context, Locale? locale) {
    _currentLocale = locale;
    updateCurrentLanguageCode(locale?.languageCode).then((value) {
      AppLocaleNotification("message").dispatch(context);
    });
  }

  Future<bool> updateCurrentLanguageCode(String? languageCode) {
    return LocalStorage.getShared().then((shared) {
      if (languageCode != null) {
        return shared.getPrefs().setString("languageCode", languageCode);
      } else {
        return shared.getPrefs().remove("languageCode");
      }
    });
  }

  Future<String?> getCurrentLanguageCode() {
    return LocalStorage.getShared().then((shared) {
      var languageCode = shared.getPrefs().getString("languageCode") ?? "en";
      return languageCode;
    });
  }
}
